package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.entity.LoginUser;
import com.example.entity.UserDTO;
import com.example.entity.UserVO;
import com.example.interceptor.JwtIgnore;
import com.example.utils.JwtTokenUtil;
import com.example.utils.TokenUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * SpringBoot整合JWT搞定跨站点统一登录
 */
@RestController
public class UserController {

    @JwtIgnore
    @PostMapping("/login")
    public UserVO login(@RequestBody UserDTO userDTO, HttpServletResponse response) {
        // 参数合法性验证
        if(!("XiaoXueJIGG".equals(userDTO.getUserNo()) && "123456".equals(userDTO.getUserPwd()))){
            throw new RuntimeException("用户名或者密码不正确!");
        }

        // todo...此处为了演示，用户写死，可以改成从数据库获取用户信息，进行用户、密码验证
        // 将用户信息加密成token，并返回给客户端
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId("1");
        loginUser.setUserNo("XiaoXueJIGG");
        loginUser.setUserName("XiaoXueJi");
        String token = JwtTokenUtil.createToken(JSONObject.toJSONString(loginUser));
        // 设置响应头
        response.setHeader(JwtTokenUtil.AUTH_HEADER_KEY, token);

        // 定义返回结果
        UserVO result = new UserVO();
        result.setUserNo("XiaoXueJIGG");
        result.setUserName("XiaoXueJi");
        return result;
    }

    /**
     * 登录成功之后，测试token信息
     */
    @GetMapping("/query")
    public LoginUser add() {
        // 获取登录的用户信息
        LoginUser loginUser = TokenUtil.getLoginUserByToken();
        System.out.println(loginUser.toString());
        return loginUser;
    }
}
